package com.jlastu.znb.adapter;


import static android.view.View.GONE;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jlastu.znb.R;
import com.jlastu.znb.buy.buyItem;
import com.jlastu.znb.view.fkActivity;

import java.util.List;
import java.util.Locale;

public class buyAdapter extends ArrayAdapter<buyItem> {
    private Context context;
    private List<buyItem> buyItems;

    public buyAdapter(Context context, List<buyItem> buyItems) {
        super(context, R.layout.buy_item, buyItems);
        this.context = context;
        this.buyItems = buyItems;
//        super(context, 0, buyItems);
//        this.context = context;
//        this.buyItems = buyItems;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 复用convertView以优化性能
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.buy_item, parent, false);
        }

        buyItem buyItem = buyItems.get(position);

        ImageView itemImageView = convertView.findViewById(R.id.imageViewProduct2);
        TextView itemNameView = convertView.findViewById(R.id.buy_item_name);
        TextView itemPriceView = convertView.findViewById(R.id.buy_item_price);
        TextView itemQuantityView = convertView.findViewById(R.id.buy_item_quantity);
        Bitmap bitmap = buyItem.getBitmap();
        Button qzfButton = convertView.findViewById(R.id.qzf);
        qzfButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取当前点击的商品项的 buyItem 对象
                buyItem currentItem = buyItems.get(position);
                Intent intentToFK = new Intent(context, fkActivity.class);
                intentToFK.putExtra("GOODS_ID", currentItem.getGoodsId());
                context.startActivity(intentToFK);
            }
        });
        if (!buyItem.hasImage()) {
            convertView.setVisibility(GONE);
            itemImageView.setVisibility(GONE);
        } else {
            convertView.setVisibility(View.VISIBLE);
            itemImageView.setImageBitmap(buyItem.getBitmap());
        }
        if (itemImageView != null && bitmap != null) {
            itemImageView.setImageBitmap(bitmap);
        } else if (itemImageView != null ){
            itemImageView.setImageResource(R.drawable.xiandou);
        }
        itemNameView.setText(buyItem.getGoodsName());
        itemPriceView.setText(String.format(Locale.getDefault(), "¥ %.2f", buyItem.getGoodsPrice()));
        itemQuantityView.setText(String.valueOf(buyItem.getQuantity()));

        return convertView;
    }
}